package net.yebaihe.wc;

import java.util.HashMap;

import net.yebaihe.wc.DataMan.MSGTYPE;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class NearBy extends StateMachine{
	ListView lstNearby;
	SQLiteDatabase listdb;
	private ListView lstDiscount;
	private ListView lstHots;
    TabHost tabHost;

	class RestaurantSimpleCursorAdapter extends SimpleCursorAdapter{

		public RestaurantSimpleCursorAdapter(NearBy nearBy, int itemnearby,
				Cursor c, String[] strings, int[] is) {
			super(nearBy,itemnearby,c,strings,is);
		}
		
		@Override  
		public void bindView(View view, Context context, Cursor cursor) {  
			super.bindView(view, context, cursor);
			if (cursor.getPosition() % 2==0){
				view.setBackgroundResource(R.drawable.rest_bg_1);
			}
			else{
				view.setBackgroundResource(R.drawable.rest_bg_2);
			}
			TextView v=(TextView) view.findViewById(R.id.txtstyle);
			Cursor c=listdb.rawQuery("select * from style where _id in (select style from style_restaurant where restaurant="+cursor.getLong(0)+")", null);
			String txt="";
			while (c.moveToNext()){
				if (txt.length()<=0){
					txt+=c.getString(1);
				}
				else{
					txt+=","+c.getString(1);
				}
			}
			c.close();
			v.setText(txt);
			
		}
		
	}
	
	private OnItemClickListener changetodish=new OnItemClickListener(){
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1,
				int arg2, long id) {
			getWCAppContext().restaurant=id;
			changeToActivity(Dishes.class);
		}
	};
	private OnItemLongClickListener addToFavorate=new OnItemLongClickListener(){
		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
				int arg2, long arg3) {
			if (getWCAppContext().email.length()<=0){
				Toast.makeText(NearBy.this, "要收藏餐厅，请先登录!", Toast.LENGTH_SHORT).show();
				return false;
			}
			Cursor c=listdb.rawQuery("select name from restaurants where _id="+arg3, null);
			c.moveToFirst();
			final String name=c.getString(0);
			final long id=arg3;
			new AlertDialog.Builder(NearBy.this).setTitle(R.string.app_name).setMessage("是否将"+name+"加入收藏")
				.setNegativeButton("否", null)
				.setPositiveButton("是", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						UserInfoData userinfo = MyHelper.get(NearBy.this).getCurrUserInfoData(getWCAppContext().email);
						MyHelper.get(NearBy.this).addFavoriteRestaurant(id,userinfo._id);
						Toast.makeText(NearBy.this,name+"已加入收藏", Toast.LENGTH_SHORT).show();
					}
				}).create().show();
			c.close();
			return true;
		}
	};
	
	@Override
	protected String getTopbarTitle() {
		return "附近";
	}

	@Override
	public void onBackPressed(){
		//listdb.close();
		super.onBackPressed();
	}
	
	@Override
	protected void prepareClient(View client) {
		listdb=MyHelper.get(this).getReadableDatabase();
		
        View btnNearBy=LayoutInflater.from(this).inflate(R.layout.btnnearby, null);
        View btnHots=LayoutInflater.from(this).inflate(R.layout.btnhots, null);
        View btnDiscount=LayoutInflater.from(this).inflate(R.layout.btndiscount, null);
		
        LinearLayout tab1=(LinearLayout)this.findViewById(R.id.tab1);
        LinearLayout lstnearby = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.lstnearby, null);
		lstNearby=(ListView) lstnearby.findViewById(R.id.lstnearby);
		lstNearby.setOnItemClickListener(changetodish);
		lstNearby.setOnItemLongClickListener(addToFavorate);
        tab1.addView(lstnearby,new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));        
		refreshNearbyList();

        LinearLayout tab3=(LinearLayout)this.findViewById(R.id.tab3);
        LinearLayout lstdiscount = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.lstnearby, null);
		lstDiscount=(ListView) lstdiscount.findViewById(R.id.lstnearby);
        tab3.addView(lstdiscount,new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));        
		//refreshNearbyList();
        lstDiscount.setOnItemClickListener(changetodish);
        lstDiscount.setOnItemLongClickListener(addToFavorate);

        LinearLayout tab2=(LinearLayout)this.findViewById(R.id.tab2);
        LinearLayout lsthots = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.lstnearby, null);
		lstHots=(ListView) lsthots.findViewById(R.id.lstnearby);
        tab2.addView(lsthots,new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));        
        lstHots.setOnItemClickListener(changetodish);
        lstHots.setOnItemLongClickListener(addToFavorate);
		
		
        tabHost=(TabHost) client.findViewById(R.id.tabhost);
        tabHost.setup();
        tabHost.addTab(tabHost.newTabSpec("nearby").setContent(R.id.tab1).setIndicator(btnNearBy));
        tabHost.addTab(tabHost.newTabSpec("hots").setContent(R.id.tab2).setIndicator(btnHots));
        tabHost.addTab(tabHost.newTabSpec("discount").setContent(R.id.tab3).setIndicator(btnDiscount));
        tabHost.setOnTabChangedListener(new OnTabChangeListener(){
			@Override
			public void onTabChanged(String tabId) {
				if (tabId.equals("hots")){
					refreshHotsList();
				}
				else if (tabId.equals("discount")){
					refreshDiscountList();
				}
				else{
					refreshNearbyList();
				}
			}
        });
        tabHost.setCurrentTab(0);
	}

	protected void refreshDiscountList() {
		String sql="select _id,name,('人均' || avgprice || '元') as avgprice,discountdesc,style,(round(length,2) || '公里') as length from restaurants where city='"+this.getWCAppContext().city+"' "+getWCAppContext().otherRestaurantSql+" order by discount desc";
		refreshRestaurantListView(lstDiscount,sql);
	}

	private void refreshRestaurantListView(ListView lv, String sql) {
		if (listdb!=null){
			Cursor c=listdb.rawQuery(sql, null);
			startManagingCursor(c);
			ListAdapter listAdapter = new RestaurantSimpleCursorAdapter(this, R.layout.itemnearby,
					c,
					new String[]{"name","avgprice","discountdesc","style","length"},
					new int[]{R.id.txtname,R.id.txtavgprice,R.id.txtdiscount,R.id.txtstyle,R.id.txtlength});
			lv.setAdapter(listAdapter);
			//db.close();
		}
	}

	protected void refreshHotsList() {
		String sql="select _id,name,('人均' || avgprice || '元') as avgprice,discountdesc,style,(round(length,2) || '公里') as length from restaurants where city='"+this.getWCAppContext().city+"' "+getWCAppContext().otherRestaurantSql+" order by ordertimes desc";
		refreshRestaurantListView(lstHots,sql);
	}

	private void refreshNearbyList() {
		SQLiteDatabase db = MyHelper.get(this).getWritableDatabase();
		if (db!=null){
			Cursor c=db.rawQuery("SELECT * FROM restaurants", null);
			if (c.moveToFirst()){
				do{
					double len=this.getWCAppContext().distance(this.getWCAppContext().getBestLat(), this.getWCAppContext().getBestLon(), 
							c.getDouble(6), c.getDouble(5), 'K');
					ContentValues initValues = new ContentValues();
					initValues.put("length",len);
					db.update("restaurants", initValues, "_id="+c.getInt(0), null);
				}while (c.moveToNext());
			}
			c.close();
			db.close();
		}
		String sql="select _id,name,('人均' || avgprice || '元') as avgprice,discountdesc,style,(round(length,2) || '公里') as length from restaurants where city='"+this.getWCAppContext().city+"' "+getWCAppContext().otherRestaurantSql+" order by length";
		refreshRestaurantListView(lstNearby,sql);		
	}

	@Override
	public void HandleMessage(MSGTYPE msgtype, boolean ret,
			HashMap<String, String> params) {
		super.HandleMessage(msgtype, ret, params);
		switch (msgtype){
		case CITY_CHANGE:
	        tabHost.setCurrentTab(0);	
	        this.refreshNearbyList();
		break;
		}
	}

	@Override
	public void onDestroy(){
		listdb.close();
		super.onDestroy();
	}
	
	@Override
	protected int getLayoutRes() {
		return R.layout.nearby;
	}

}
